#ifndef _ACCEPT_LINK_MANAGER_H_
#define _ACCEPT_LINK_MANAGER_H_
#include "link_manager.h"
#include "event.h"
#include <QTcpSocket>
#include <QMap>
#include <QQueue>

class QTcpSocket;
class FileManager;
class QUrl;
class AcceptLinkManager: public BaseLinkManager
{
	Q_OBJECT
	typedef void (AcceptLinkManager::*net_handler_t)(void *buffer);
public:
	AcceptLinkManager(FileManager *fileManager,
		   const QUrl &url,	QObject *parent = NULL);
	~AcceptLinkManager();
	void stop();
	void cleanUp();
protected:
	void run();
	void onRespondRegisterUser(void *buffer);
	void onRespondRegisterUrl(void *buffer);
	void onRespondFriend(void *buffer);
	void onRespondDownloadUrl(void *buffer);
	void onRespondFileInfo(void *buffer);
	void onRespondDownloadSection(void *buffer);
protected slots:
	void onConnect();
	void onDisconnect();
	void onRead();
private:
	typedef QMap<int, net_handler_t> NetHandlerMap;
	NetHandlerMap netHandlers;
	void startConnect();
	FileManager *fileManager;
	QByteArray urlByteArray;
	QUrl url;
	bool gotPiece;
	int pieceIndex;
	int retry;
	qint64 offset;
	size_t buf_size;
	char buffer[MAX_EVENT_LENGTH];
	QTcpSocket *socket;
	struct Peer {
		QString globalIp;
		QString localIp;
		quint16 port;
	};
	QQueue<Peer> netPeers;
	bool connecting_to_peer; // 0 for server, 1 for peer.
};

#endif // _ACCEPT_LINK_MANAGER_H_
